<?php
require_once "handler.class.php";

/**
 * Handler-class for FOREACH template tag. To be rewritten?
 */
class qForeachHandler extends qHandler
{
    /**
     * Constuctor.
     */
    function __construct()
    {
        $this->iscloseable = true;
        $this->parsechildren = false;
    }
    
    /**
     * Parses tag.
     * @see qHandler.
     */
    public function Parse($tag, $body)
    {
        // get parameter string
        $parameter = mb_substr($tag, 9, -1);
        // syntax: $element in $array
        $preg = '/\$([a-zA-Z0-9\.]+) in \$([a-zA-Z0-9\.]+)/';
        
        // get variables and subkeys
        $subkeys = qTemplateParser::Subkeys();
        $values = qTemplateParser::Values();
        
        preg_match($preg, $parameter, $array);
        
        $newbody = '';
        // for all subelements of array, parse it replacing elem var name with "true" var name and parse it
        foreach ($subkeys[$array[1]] as $subkey)
        {
            $newbody .= qTemplateParser::Parse(preg_replace('/\$'.$array[0].'([^a-zA-Z0-9])/', '$'.$subkey.'\\1', $body));
        }
        
        return array(true, $newbody);
    }
}